package com.book;

/*
 * @author:周洋帆
 * @param
 *     keyWrod：关键词。
 *     result:返回的结果。结果是是一个数组，里面的元素是以键值对存在。在本实例中是图书书名和图书url。
 * @see
 *     getXXX方法：用与struts的json插件返回json对象（在struts.xml配置）。
 *       本实例中设置root为result，所以getResult传递json对象。KeyWord的set和get方法
 *       用于struts的jsp与服务器之间自动传递参数。
 *     execute方法：根据关键词搜索索引，获取结果赋值给result，返回json对象。
 *  
 */

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.opensymphony.xwork2.ActionSupport;

public class BookSearchAction extends ActionSupport{
	private String keyWord;
	private List<Map<String,String>> result=new ArrayList<Map<String,String>>();
	public void setKeyWord(String keyWord){
		this.keyWord=keyWord;
	}
	public String getKeyWord(){
		return keyWord;
	}
	
	public List<Map<String,String>> getResult(){
		return result;
	}
	public String execute(){
		File f=new File("d:/MySQL/index/newBook");
		int numTotalHits=0;
		try {
			IndexSearcher searcher=new IndexSearcher(DirectoryReader.open(FSDirectory.open(f)));
			Analyzer analyzer = new IKAnalyzer();
 		    QueryParser parser = new QueryParser(Version.LUCENE_4_10_0, "title", analyzer);		
			Query query=parser.parse(keyWord);
			TopDocs hits=searcher.search(query,4);
			numTotalHits = hits.totalHits;
			System.out.println(numTotalHits);
			for(ScoreDoc doc:hits.scoreDocs){
				Document d=searcher.doc(doc.doc);
				Map<String,String> temp=new HashMap<String,String>();
				temp.put("title", d.get("title"));
				temp.put("url", d.get("url"));
				result.add(temp);
				
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "success";
	}
}
